var msg1 = "Periodic nozzle wiping will automatically clean the nozzle during printing.<br>"
var msg2 = "This happens at layer changes and is helpful for oozy materials<br>"
var msg3 = "like ULTEM, PEI, PPSU, or long prints with any material."
var message = var.msg1 ^ var.msg2 ^ var.msg3

M291 S4 R"Periodic Nozzle Wiping" P{var.message} K{"Configure Frequency","Disable"} F0

if input = 1
    ; Disable periodic wiping
    echo >"0:/sys/user/variables/PeriodicWiping.g" "set global.periodicWiping = 0 ; Periodic wiping disabled"
    
    ; Reset layer counter
    set global.periodicWipingLayerCount = 0
    
    echo "Periodic wiping is now disabled"
    M291 S1 R"Disabled" P"Periodic nozzle wiping has been disabled." T5
    abort

; User chose to configure - show frequency options
var freq_msg = "How often should the nozzle be wiped?<br><br>Every Layer = Most thorough, adds time<br>Every 2nd = Good balance<br>Every 5th = Minimal impact<br>Custom = Specify your own interval"

M291 S4 R"Wipe Frequency" P{var.freq_msg} K{"Every Layer","Every 2nd Layer","Every 5th Layer","Custom"} F0

var frequency = 1

if input = 0
    set var.frequency = 1
elif input = 1
    set var.frequency = 2
elif input = 2
    set var.frequency = 5
else
    ; Custom frequency
    M291 S6 R"Custom Frequency" P"Enter the number of layers between each wipe:<br>(Recommended: 2-10 layers)" L1 H50 F5
    set var.frequency = input

; Save the configuration
echo >"0:/sys/user/variables/PeriodicWiping.g" "set global.periodicWiping = " ^ var.frequency ^ "; Periodic wiping every " ^ var.frequency ^ " layer(s)"

; Load the new settings
M98 P"0:/sys/user/variables/PeriodicWiping.g"

; Reset layer counter
set global.periodicWipingLayerCount = 0

var freq_text = "every layer"
if var.frequency > 1
    set var.freq_text = "every " ^ var.frequency ^ " layers"

echo "Periodic wiping enabled: " ^ var.freq_text
M291 S1 R"Enabled" P{"Periodic nozzle wiping is now enabled<br>" ^ var.freq_text ^ "."} T5